package com.tisco;

import com.domain.InitDomain;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TransferServer {

    private int port ;// 默认服务器端口
    private String location ;
//    private FileOutputStream fos;

    private InitDomain initDomain;

    // 创建指定端口的服务器
    public TransferServer(int port) {
        this.port = port;
    }

    public TransferServer(InitDomain initDomain) {
        this.initDomain = initDomain;
        this.port = initDomain.getPort();
        this.location = initDomain.getLocation();
    }
    // 提供服务
    public void service() {
        int i = 0;
        try {
            // 建立服务器连接,设定客户连接请求队列的长度
            ServerSocket server = new ServerSocket(port, 100);

            while (true) {
                // 等待客户连接
                Socket socket = server.accept();
                i++;
                System.out.println("第" + i + "个Socket连接成功！");
                new Thread(new ServerThread(socket, i,initDomain)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {
        private int index;
        private Socket socket;
        private InitDomain initDomain;

        private DataInputStream dis;

        private FileOutputStream fos;

        public ServerThread(Socket socket, int i,InitDomain initDomain) {
            this.socket = socket;
            this.index = i;
            this.initDomain = initDomain;
        }
        // 任务是为一个用户提供服务
        @Override
        public void run() {
            try {
                dis = new DataInputStream(socket.getInputStream());

                // 文件名和长度
                String fileName = dis.readUTF();
                long fileLength = dis.readLong();
                File directory = new File(initDomain.getLocation());
                if(!directory.exists()) {
                    directory.mkdir();
                }
                File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
                fos = new FileOutputStream(file);
                // 开始接收文件
                byte[] bytes = new byte[1024];
                int length = 0;
                while((length = dis.read(bytes, 0, bytes.length)) != -1) {
                    fos.write(bytes, 0, length);
                    fos.flush();
                }
                if(dis!=null){
                    dis.close();
                }
                if(fos!=null){
                    fos.close();
                }
            } catch (Exception e) {
                System.out.println("Socket断开连接");
            } finally {
                try {
                    if(fos != null)
                        fos.close();
                    if(dis != null)
                        dis.close();
                    socket.close();
                } catch (Exception e) {}
            }
        }
    }
}
